import React, {useEffect, useRef, useState} from "react"
import {Button, Card, Cascader, Col, DatePicker, Form, Input, InputNumber, message, Row, Select} from 'antd';
import {fetch, MethodEnum, Navigation, useCurrentRoute, useStore} from "f22";
import {diSubjects, SubjectPo} from "../../subject/SubjectManage";
import Questions from "./Questions";
import {PaperPo, QuestionPo} from "../../../../types";
import moment from "moment"

const {Option} = Select;

const formItemLayout = {
  labelCol: {span: 6},
  wrapperCol: {span: 12},
};

const getPathArray = (key: number, items: any) => {
  const result: any[] = []
  const di = (k, is) => {
    const r = is.find(i => {
      if (i.id === k) return true
      if (i.children) return di(k, i.children)
    })
    if (r) result.unshift(r)
    return r
  }
  di(key, items)
  return result;
}


export default (() => {
  const [subjectData, setSubjectData] = useState<SubjectPo[]>([])
  const [questions, setQuestions] = useState<QuestionPo[]>([])
  const questionRef = useRef<any>();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false)
  const paperId = Navigation.params().paperId
  const {dispatch} = useStore("routerTabs")
  const currentRouter = useCurrentRoute() // 当前路由
  const [paper, setPaper] = useState<PaperPo | null>()
// 可以保存
  const canSave = () => {
    return paper == null || paper.releaseStatus !== 1
  }
  // 编辑模式？
  useEffect(() => {
    if (!paperId || !subjectData.length) return;
    fetch<PaperPo>({
      method: MethodEnum.GET,
      url: "/admin/paper/" + paperId
    }).then(data => {
      const paper = data.response;
      setPaper(paper)
      form.setFieldsValue({
        paperName: paper.paperName,
        paperTypeId: paper.paperTypeId,
        year: moment(`${paper.year}-1-1`),
        time: paper.time,
        subjectId: getPathArray(paper.subjectId, subjectData).map(item => item.id)
      })
      setQuestions(paper.questions?.map(item => {
        return {...item, options: JSON.parse(item.options as string)}
      }) as QuestionPo[])
    })
  }, [paperId, subjectData])

  // 学科数据
  useEffect(() => {
    fetch<SubjectPo[]>({
      method: MethodEnum.GET,
      url: "/subject/all"
    }).then(data => {
      setSubjectData(diSubjects(data.response))
    })
  }, [])


  // 保存
  const save = async () => {
    await form.validateFields();
    const questions: QuestionPo[] = questionRef.current.sendQuestion()
    if (!questions.length) return message.error("请为试卷最少设置一道题目")
    const paperValues = form.getFieldsValue();
    const paper: any = {
      ...paperValues,
      subjectId: paperValues.subjectId[paperValues.subjectId.length - 1],
      year: paperValues.year.get("year"),
      questions: questions.map(item => {
        return {...item, options: JSON.stringify(item.options)}
      }) as QuestionPo[]
    }
    if (paperId) {  // 编辑模式
      paper.id = paperId
      setLoading(true)
      fetch({
        request: paper,
        method: MethodEnum.PUT,
        url: "/admin/paper/edit",
        notLoading: true
      }).then(() => {
        message.success("试卷编辑成功")
        Navigation.push("/Paper")
        dispatch("minus", currentRouter)
      }).finally(() => setLoading(false))
    } else {     // 新增
      setLoading(true)
      fetch({
        request: paper,
        method: MethodEnum.POST,
        url: "/admin/paper/add",
        notLoading: true
      }).then(() => {
        message.success("试卷新建成功")
        Navigation.push("/Paper")
        dispatch("minus", currentRouter)
      }).finally(() => setLoading(false))
    }

  }

  return (
    <Row gutter={20}>
      {
        canSave() ?
          <Col span={24} style={{padding: "12px", textAlign: "right"}}>
            <Button type="primary" onClick={() => save()} loading={loading}>保存试卷</Button>
          </Col> : null
      }

      <Col span={8}>
        <Card title="试卷基础信息">
          <Form
            form={form}
            name="validate_other"
            {...formItemLayout}
          >
            <Form.Item
              name="paperName"
              label="试卷名称"
              hasFeedback
              rules={[{required: true, message: '请选择试卷类型'}]}
            >
              <Input placeholder="请输入试卷名称"/>
            </Form.Item>
            <Form.Item
              name="subjectId"
              label="所属学科"
              hasFeedback
              rules={[{required: true, message: '请选择所属学科'}]}
            >
              <Cascader options={subjectData} placeholder="请选择学科"/>
            </Form.Item>
            <Form.Item
              name="paperTypeId"
              label="试卷类型"
              hasFeedback
              rules={[{required: true, message: '请选择试卷类型'}]}
              initialValue={1}
            >
              <Select placeholder="请选择试卷类型">
                <Option value={1}>历年真题</Option>
                <Option value={2}>模拟试题</Option>
              </Select>
            </Form.Item>
            <Form.Item
              name="year"
              label="试卷年份"
              hasFeedback
              rules={[{required: true, message: '请选择试卷年份'}]}
            >
              <DatePicker picker="year" allowClear/>
            </Form.Item>
            <Form.Item label="考试时长">
              <Form.Item name="time" noStyle rules={[{required: true, message: '请输入考试时长'}]} hasFeedback>
                <InputNumber min={1} max={10000}/>
              </Form.Item>
              <span className="ant-form-text"> 分钟</span>
            </Form.Item>
          </Form>
        </Card>
      </Col>
      <Col span={16}>
        <Questions ref={questionRef} questions={questions}/>
      </Col>
    </Row>
  );
});
